package cn.edu.neu.utils;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

public class FileUploadUtil {
    /**
     * 文件上传
     */
    public static Map  uploadFile(MultipartFile uploadfile,String path ) {
//		System.out.println("=========dirPath=1111");
        Map map=new HashMap<>();
        try {
            // 获取文件名以及后缀名
            String fileName = uploadfile.getOriginalFilename();
            // 重新生成文件名（根据具体情况生成对应文件名）
            SimpleDateFormat formatter = new SimpleDateFormat("YYYYMMDDHHmmssSSS");
            Calendar calendar = Calendar.getInstance();
            System.out.println(formatter.format(calendar.getTime()));
//			fileName = UUID.randomUUID()+"_"+fileName;
            fileName=formatter.format(calendar.getTime())+"_"+fileName;
            // 指定上传文件本地存储目录，不存在需要提前创建
            File directory = new File("src/main/resources");
            String reportPath = directory.getCanonicalPath();
            String dirPath = reportPath+path;
            System.out.println("=========dirPath"+dirPath);
            File filePath = new File(dirPath);
            if(!filePath.exists()){
                filePath.mkdirs();
            }


            uploadfile.transferTo(new File(dirPath+fileName));
            map.put("msg","success");
            map.put("cate_pic","/images/cate/"+fileName);

        } catch (Exception e) {
            e.printStackTrace();
            // 上传失败，返回失败信息
            map.put("msg","fail");
        }

        System.out.println("=========dirPath=13333");
        // 携带上传状态信息回调到文件上传页面
        return map;
    }
}
